package x.trident.core.micro.core.context;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import x.trident.core.micro.api.constants.MicroConstants;
import x.trident.core.pojo.request.BaseRequest;
import x.trident.core.util.HttpServletUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前请求的请求号，没有请求号则生成空串
 *
 * @author Seven
 * @date 2018-05-09-下午6:25
 */
@Slf4j
public class RequestNoContext {
    private RequestNoContext() {
    }

    public static String getRequestNoByHttpHeader() {
        HttpServletRequest request = HttpServletUtil.getRequest();

        if (request == null) {
            if (log.isDebugEnabled()) {
                log.info("获取请求号失败，当前不是http请求环境！");
            }
            return "";
        } else {
            String requestNo = request.getHeader(MicroConstants.REQUEST_NO_HEADER_NAME);
            return StrUtil.isNotEmpty(requestNo) ? requestNo : "";
        }
    }

    /**
     * 通过请求参数获取requestNo，参数必须是AbstractBaseRequest的子类
     */
    public static String getRequestNoByRequestParam(Object[] params) {

        if (params != null && params.length > 0) {
            for (Object paramItem : params) {
                if (paramItem instanceof BaseRequest) {
                    BaseRequest baseRequest = (BaseRequest) paramItem;
                    return baseRequest.getRequestNo();
                }
            }
        }
        return "";
    }

}
